<template>
    <div class="level-discount" :level="levelFormat.level" :blank="blank" :currency="levelFormat.currency">
        <span v-for="item in labelList" :key="item.name" :name="item.name" v-text="item.value"></span>
        <slot></slot>
    </div>
</template>
<script>
import { mapGetters, mapState } from "vuex";
export default {
    name: "LevelDiscount",
    props: {
        // 价格，美分
        price: { type: [String, Number], default: 0 },
        // 是否是空白模板，如果是空白模板，则打95折
        blank: { type: Boolean, default: false },
        // 等级，用于在订单时表现，有可能下单时等级和当前等级不一至
        level: { type: [Object, String, Number], default: () => null },
        // 数量，默认为1
        count: { type: Number, default: 1 },
        // 显示类型 <unit><original><discount><icon>
        type: { type: String, default: '' },
        // 其他内容
        other: { type: Object, default: () => ({}) },
    },
    data () {
        return {
            priceSplit: /-+/,
        };
    },
    watch: {
        level: {
            immediate: true,
            handler () {
                // 已登录状态下,检查更新用户等级
                if (process.client && this.$store.state.token && this.level) {
                    const user = this.$store.state.user || {}
                    const level = this.level.user_level || this.level;

                    const parentname = this.$parent._name;
                    const lisition = ['product', 'product-detail', 'designer', 'user-template', 'user-template-detail', 'user-store']

                    // if (parentname != '<OrderUnpaidProduct>' && parentname != '<ProductList>' && user.level != level) {
                    if (lisition.indexOf(this.$route.name) >= 0 && user.level != level) {
                        this.$store.commit('user/SET_USER_LEVEL', {
                            level: level,
                            discount: this.level.user_discount || 100,
                        });
                    }
                }
            }
        }
    },
    computed: {
        ...mapState({
            currency: 'currency',
            rate: 'rate',
        }),
        ...mapGetters({
            isLogin: "getIsLogin",
        }),
        // 显示列表
        labelList () {
            const result = [];
            // 默认情况
            const type = !this.type ? 'unit|original|discount|icon' : this.type;

            type.split('|').map(str => {
                str == 'unit' && result.push({ name: str, value: this.levelFormat.currency });
                str == 'original' && result.push({ name: str, value: this.getOriginalPrice(this.price) });
                str == 'discount' && result.push({ name: str, value: this.getDiscountPrice(this.price) });
                str == 'icon' && result.push({ name: str, value: '' });
                str == 'label' && result.push({ name: str, value: this.getDiscountLabel() });
                this.other[str] && result.push({ name: str, value: this.other[str] });

            });


            return result;
        },

        levelFormat () {
            const default_discount = {
                1: 100,
                2: 97,
                3: 95,
                4: 94,
                5: 92,
                6: 91,
                7: 90,
            }

            // 如果用户信息中有，则取用户信息中的
            const currency = (this.level || {}).currency || this.currency;
            const rate = (this.level || {}).rate || this.rate || 1;

            // 未登录状态下都是等级1
            if (this.isLogin && this.level) {
                const level = Math.max(1, Math.min(7, parseInt(this.level.user_level || this.level) || 1))
                const discount = parseInt(this.level.user_discount) || default_discount[level];
                return {
                    level: level,
                    discount: discount,
                    currency: currency,
                    rate: rate,
                }
            } else {
                return {
                    level: 1,
                    discount: 100,
                    currency: currency,
                    rate: rate,
                }
            }

        },
    },
    methods: {
        mathRound (value, n = 2) {
            n = n === undefined ? 1 : n;
            let bei = Math.pow(10, n);
            let res = Math.round(value * bei) / bei;
            return +parseFloat(res.toPrecision(12));
        },
        getDiscountLabel () {
            const discount = this.levelFormat.discount
            return (100 - discount) + '% off'
        },

        // 价格
        getPrice (price, isDiscount) {
            const priceFormat = parseInt(price);
            const blankDiscount = this.blank ? 0.95 : 1;
            const userDiscount = this.levelFormat.discount;

            if (isNaN(priceFormat)) {
                return ''
            } else if (!isDiscount) {
                // 当等级为1时，显示原价
                return this.mathRound(0.01 * priceFormat * this.count * this.levelFormat.rate).toFixed(2);
            } else {

                // 空白模板先向上取整
                const blank = Math.ceil(blankDiscount * priceFormat);
                const price = this.mathRound(blank * 0.01 * userDiscount);

                return (0.01 * Math.round(price) * this.count * this.levelFormat.rate).toFixed(2);
            }
        },

        // 原价
        getOriginalPrice (price) {
            if (typeof price === 'string' && this.priceSplit.test(price)) {
                // 显示价格区间
                return price.replace(/[\d\.]+/g, i => this.getPrice(i, false))
            } else {
                return this.getPrice(price, false);
            }
        },
        // 折扣价
        getDiscountPrice (price) {
            if (typeof price === 'string' && this.priceSplit.test(price)) {
                return price.replace(/[\d\.]+/g, i => this.getPrice(i, true))
            } else {
                return this.getPrice(price, true);
            }
        },
    },
};
</script>
<style lang="scss" scoped>
.level-discount {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-family: Roboto;
    font-size: 16px;
    color: #000000;
    line-height: 18px;
    font-weight: 400;

    span {
        vertical-align: top;
        white-space: nowrap;

        &+span {
            margin-left: 4px;
        }
    }

    // 单位
    span[name='unit'] {
        color: #000000;
    }

    // 原价
    span[name='original'] {
        color: #000000;
        text-decoration: line-through;
    }

    // 会员价
    // span[name='discount'] {
    // }

    // 图标
    span[name='icon'] {
        width: 18px;
        height: 18px;
        background-size: 18px 18px;
        background-position: center center;
        background-repeat: no-repeat;
    }

    &[level='1'] {

        span[name='original'],
        span[name='icon'] {
            display: none;
        }
    }

    &[level='2'] {
        color: #a88965;
        border-color: #a88965;

        span[name='icon'] {
            display: inline-block;
            background-image: url(@/assets/images/level-icon2.png);
        }
    }

    &[level='3'] {
        color: #748391;
        border-color: #748391;

        span[name='icon'] {
            display: inline-block;
            background-image: url(@/assets/images/level-icon3.png);
        }
    }

    &[level='4'] {
        color: #cc930c;
        border-color: #cc930c;

        span[name='icon'] {
            display: inline-block;
            background-image: url(@/assets/images/level-icon4.png);
        }
    }

    &[level='5'] {
        color: #2e91b3;
        border-color: #2e91b3;

        span[name='icon'] {
            display: inline-block;
            background-image: url(@/assets/images/level-icon5.png);
        }
    }

    &[level='6'] {
        color: #d5417a;
        border-color: #d5417a;

        span[name='icon'] {
            display: inline-block;
            background-image: url(@/assets/images/level-icon6.png);
        }
    }

    &[level='7'] {
        color: #9878d1;
        border-color: #9878d1;

        span[name='icon'] {
            display: inline-block;
            background-image: url(@/assets/images/level-icon7.png);
        }
    }
}
</style>
